package com.example.powernodemall.filter;

import com.example.powernodemall.constant.BaseConstant;
import com.example.powernodemall.model.SecurityUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.time.Duration;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class TokenFilter extends OncePerRequestFilter {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    ObjectMapper objectMapper;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestHeader = request.getHeader(BaseConstant.AuthHeader);
        if (requestHeader==null){
            return;
        }
        requestHeader = requestHeader.substring(7);
        if (requestHeader.isBlank()){
            return;
        }
        Long expire = stringRedisTemplate.getExpire(BaseConstant.Redis_Token_Prefix+requestHeader);
        if (expire<BaseConstant.ToKen_Expire_Limit){
            stringRedisTemplate.expire(requestHeader, Duration.ofSeconds(BaseConstant.Token_Expire));
        }
        String string = stringRedisTemplate.opsForValue().get(BaseConstant.Redis_Token_Prefix+requestHeader);
        SecurityUser securityUser = objectMapper.readValue(string, SecurityUser.class);
        Set<String> roles123 = securityUser.getRoles123();
        Set<SimpleGrantedAuthority> authorities = roles123.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(securityUser,null,authorities);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        filterChain.doFilter(request, response);
    }
}
